立即執行函式(IIFE)的理解與運用


Posted by hoyi-23 on 2021-10-24

IIFE

IIFE 立即函式(Immediately-Invoked Function Expression)

特色

  • 立即函式可以讓函式在建立後立即執行。
  • 無法在函式外被呼叫

寫法

  1. (function(){})()
  2. (function(){}());
  3. arrow function: (()=>{})();
  4. 具名function: (function fn1(){})()
    例如:
(function fn1(){
    num++;
    console.log(num);
    return num !== 5 ? fn1(num) : console.log('finished!')
})(num = 0)

主要兩點:

  • 如果是函式表達式,可直接在其後加()執行
  • 如果是函式宣告,可以通過()+-voidnew等運算子將其轉換為函式表達式,然後再加上()立即執行。

例如:
void function(){}(alert("ok"));
在最後呼叫的"()"傳入需要的引數

使用時機

1.當我們需要寫一個js檔案,並且複用率很高的時候,建議使用。

2.如果宣告的函式只需要呼叫一次,建議使用。

3.獨立模組,這個和第一點差不多。單獨提出來,是想強調一下立即執行函式的好處,開發時,它能做到各模組的低耦合,減少對全域性作用域的汙染


  • 使用IIFE,放在內部宣告的變數可以避免汙染全域。
const x = 'global'
(()=>{
    const x = 'IIFE';
    console.log(x)
})(); // IIFE

console.log(x) // global
  • Private Variable and Methods from Closure
const increment = (()=>{
    let counter = 0;
    console.log(`counter ${counter}`);
    const credit = (num) => console.log(`I have ${num} credit(s).`);
    return ()=>{conter++; credit(counter)}
})(); // counter 0

increment(); // I have 1 credit(s).
increment(); // I have 2 credit(s).
  • The Module Pattern
//建立object
const Score = (()=>{
    let count = 0;

    return{
        current: ()=>{return count},
        increment: ()=>{count++},
        reset: ()=>{count = 0}
    }
})();

Score.increment();
cosole.log(Score.current()) // 1
Score.reset();
cosole.log(Score.current()) // 0
  • The Revealing Pattern is a variation of the Module Pattern
const Game = (()=>{
    let count = 0;
    const current = ()=>{ return `Game score is ${count}.`};
    const increment = ()=>{ count ++};
    const reset = ()=>{ count = 0};

    return{
        current: current,
        increment: increment,
        reset: reset
    }
})();

Game.increment();
console.log(Game.current());//1
  • Injecting a namespace object
(( namespace )=>{
    namespace.count = 0;
    namespace.current = function(){ return `App count is ${this.count}`};
    //不使用arrow,是因為要運用到this
    namespace.increment = function(){ this.count++ };
    namespace.reset = function(){
this.count = 0};
})(window.App = windowApp || {});

App.increment();
console.log(App.current())// App count is 1

#IIFE #立即函式







Related Posts

[JavaScript] ES6:Destructuring 解構

[JavaScript] ES6:Destructuring 解構

該如何入門 CTF 中的 Web 題?

該如何入門 CTF 中的 Web 題?

How to Set Up Firewall with UFW on Ubuntu 20.04

How to Set Up Firewall with UFW on Ubuntu 20.04


Comments